package com.lmind.core.gps.tm;

import java.util.List;

import com.lmind.bean.EventProvider;
import com.lmind.core.async.ResultHandler;
import com.lmind.core.gps.gateway.GatewayMessageContext;
import com.lmind.core.gps.gateway.TerminalGateway;
import com.lmind.core.gps.terminal.message.AbstractMessage;
import com.lmind.core.gps.terminal.message.ReplyMessage;
import com.lmind.core.message.AsyncMessageProcessor;

public class DefaultTerminalManager implements AsyncMessageProcessor<GatewayMessageContext, AbstractMessage>, TerminalManager {
	
	private EventProvider<TerminalManagerListener> event = new EventProvider<TerminalManagerListener>();
	
	private List<TerminalGateway> gateways;

	public List<TerminalGateway> getGateways() {
		return gateways;
	}

	public void setGateways(List<TerminalGateway> gateways) {
		this.gateways = gateways;
		if (gateways != null) {
			for (TerminalGateway gateway : gateways) {
				gateway.setProcessor(this);
			}
		}
	}
	
	@Override
	public void addTerminalManagerListener(TerminalManagerListener listener) {
		event.addEventListener(listener);
	}
	
	@Override
	public void removeTerminalManagerListener(TerminalManagerListener listener) {
		event.removeEventListener(listener);
	}
	
	public void send(String deviceSerial, AbstractMessage message, ResultHandler<ReplyMessage> handler) {
		// TODO 暂时只会有一个网关，因此不 做判断
		gateways.get(0).send(deviceSerial, message, handler);
	}

	@Override
	public void process(GatewayMessageContext context,
			AbstractMessage message, ResultHandler<AbstractMessage> handler) {
		
		for (TerminalManagerListener listener : event.toList()) {
			listener.message(context.getTerminal(), message);
		}
		
	}


}
